import * as bcrypt from 'bcryptjs';
import { AccountErrorKey } from '../constants/user.constant';

export class HashUtil {
  /**
   * string加密盐
   * @param rawVal
   * @returns
   */
  public static encryption(rawVal: string) {
    return bcrypt.hashSync(rawVal, 10);
  }

  /**
   * compare string
   * @param rawVal
   * @param hashVal
   * @returns
   */
  public static compare(rawVal: string, hashVal: string) {
    return bcrypt.compareSync(rawVal, hashVal);
  }

  /**
   * 校验密码是否正确
   * @param password 输入密码
   * @param passwordHash 密码hash值
   * @returns
   */
  public static checkPassword(password: string, passwordHash: string) {
    if (!passwordHash || !this.compare(password, passwordHash)) {
      throw new Error(AccountErrorKey.ACCOUNT_OR_PASSWORD_ERROR);
    }
    return true;
  }
}
